package com.rbac.api.interceptor.component;

import com.rbac.api.constant.AdminConstant;
import com.rbac.api.controller.enums.HintMessageEunm;
import com.rbac.api.exception.AdminAllException;
import com.rbac.api.mybatis.mapper.AdminMenusMapper;
import com.rbac.api.service.common.AdminCommonService;
import com.rbac.utils.commUtils.StringPubUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class CheckPowerComponent {

    ///操作管理员token公共service
    @Autowired
    private AdminCommonService adminCommonService;

    ///菜单表mapper
    @Autowired
    private AdminMenusMapper adminMenusMapper;



    /***
     * 根据 token 和访问地址检测权限
     * @param request
     * @throws Exception
     */
    public void checkPowerByTokenAndUrl(HttpServletRequest request) throws Exception{
        ///管理员账号
        String userAccount = adminCommonService.getUserInfoFieldByRequestHeader(request,"account");

        //如果是非超级管理员账号才检测权限
        if(!(userAccount.equals(AdminConstant.SUPER_ADMINISTRATOR_ACCOUNT_VALUE))){
            checkOrdinaryUsersPower(request);
        }
    }

    /***
     * 检测普通管理员权限（非超管用户）
     * @param request
     * @throws Exception
     */
    private void checkOrdinaryUsersPower(HttpServletRequest request) throws Exception{
        //根据request获取管理员编号
        String userNo = adminCommonService.getUserInfoFieldByRequestHeader(request,"userno");

        //获取请求的地址
        String path = request.getRequestURI();
        //去除两遍的 /
        path = StringPubUtil.trim(path,"/");
        //转换成小写
        path = path.toLowerCase();


        ///获取访问的菜单编号
        String menuNo =  adminMenusMapper.selectMenuNoByMenuAddressSelective(path);
        if(StringUtils.isEmpty(menuNo)){//提示访问路径不存在
            throw new AdminAllException(HintMessageEunm.EXCEPTION_P_MENU_NOT_EXISTS_ERROR_EXCEPTION);
        }

        ///根据管理员编号和菜单编号count是否拥有此地址权限
        Integer countRes =adminMenusMapper.checkThisAddressPowerSelective(userNo,menuNo);
        if(countRes == null || countRes.equals(0)){///提示没有访问权限
            throw new AdminAllException(HintMessageEunm.EXCEPTION_P_NOT_HAVE_ROLES_ERROR_EXCEPTION);
        }
    }




}
